import { ICmpnt, IBindEvent, EnumAction } from 'xcore/cmpnt';
import $data from 'xcode/data';
import $utils from 'xcore/utils';




export function bindForm(cmpnt: ICmpnt, event: IBindEvent): ICmpnt | undefined {
    //组件未绑定，需要先创建组件，然后设置为显示状态
    if (event.action_id && event.isBind === true) {
        return $data.func.getById(event.action_id) as ICmpnt
    }

    //创建Form
    let FormId: string = event.action_id || ""
    if (!event.action_id) {
        let form: ICmpnt | undefined = $data.func.findParent(cmpnt.id, 'form');
        if (!form) {
            $utils.msg.error("未找到Form组件")
            return undefined
        }
        FormId = form.id
        event.action_id = form.id
    }

    //绑定事件
    switch (event.action) {
        case EnumAction.FormSubmit:
            cmpnt.events[event.event] = () => {
                // find 表单对象
                let form = $data.func.getCmpntRef(FormId) as any
                if (!form) {
                    $utils.msg.error("未找到Form组件")
                    return
                }
                form.validate((valid: boolean) => {
                    if (!valid) return;
                    //获取表单数据
                    let form: ICmpnt | undefined = $data.func.findParent(cmpnt.id, 'form');
                    if (!form) {
                        $utils.msg.error("未找到Form组件")
                        return
                    }
                    let modelData = $data.store.page.meta.find(form.id)
                    //设置数据
                    $data.provider.biz.submit(modelData)
                })
            }
            break;
    }


    //设置状态

    event.action_id = FormId
    event.isBind = true
    return $data.func.getById(FormId) as ICmpnt
}
export function removeForm(cmpnt: ICmpnt, event: IBindEvent) {
    if (event.action_id && event.isBind === true) {
        delete event.action_id
        delete event.isBind
        cmpnt.events[event.event] = function () { }
    }
}